package com.tony.study.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: LockDemo01
 * @Auther: 皮蛋布丁
 * @Date: 2021/10/31/21:10
 * @Description: 测试lock锁
 */
public class LockDemo01 {

    public static void main(String[] args) {
        TestLock lock = new TestLock();
        new Thread(lock).start();
        new Thread(lock).start();
        new Thread(lock).start();
    }
}
class TestLock implements Runnable {

    int ticketNums = 10;
    //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();    //加锁
                if (ticketNums > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                } else {
                    break;
                }
            } finally {
                //解锁
                lock.unlock();
            }
        }
    }
}